<?php

namespace App\Model\Admin;
use App\Model\BaseModel;
use App\Utility\Pagination;
class Auth extends BaseModel
{
   
	function get_auth_group_page($param){			
	
		$page=!isset($param['page']) ? 0 : $param['page'];
		
		if($page!=0){			
			$get_page=$page-1;
		}else{
			$get_page=0;
		}
		
		$page_size=DbConfig('page_num');
		
		$sql='select * from osc_admin_auth_group where id>0 order by id desc';
		
		$total=count($this->db->rawQuery($sql));
		
		$sql.=" limit ".$get_page*$page_size.','.$page_size;
		
		$list=null;
		
		$list = $this->db->rawQuery($sql);
		 
		$pagination = new Pagination();
		$pagination->total = $total;
		$pagination->page = $page;
		$pagination->limit = $page_size;
		$pagination->param = $param;
		$pagination->url ='/admin/auth/index';
		
		$render = $pagination->render();		 
		 
		return ['list'=>$list,'page'=>$render,'total'=>$total];
		 
	}
	function get_by_id($id){
        $data = $this->db->where('id',$id)->getOne('osc_admin_auth_group');
        return empty($data) ? null : $data;
    }
	
	function add_group($data){
		
		if($id= $this->db->insert('osc_admin_auth_group',$data)){
			return $id;
		}else{
			return ['error'=>$this->db->getLastError()];
		}
	}
	function edit_group($data){
	
		$id=$data['id'];
		unset($data['id']);
		
		return $this->db->where('id',$id)->update('osc_admin_auth_group',$data);
		
	}
	//删除单个元素
	 function delete_group($id){
        return $this->db->where('id',$id)->delete('osc_admin_auth_group');
    }

    function set_status($data){		
		$this->db->where('id',$data['id'])->update('osc_admin_auth_group',['status'=>$data['status']]);		
	}
	function write_group($data){
		
		$group_id=(int)$data['id'];
		
		$this->db->where('group_id',$group_id)->delete('osc_admin_auth_rule');
		
	 	if(isset($data['rules'])){
            sort($data['rules']);
            $data['rules']  = implode( ',' , array_unique($data['rules']));
        }
		
		$this->db->where('id',$group_id)->update('osc_admin_auth_group',$data);
		
		$group_menu=$this->get_by_id($group_id);			

		$menu_id=explode(',', $group_menu['rules']);	
		
		$menu_list=osc_model('admin','menu')->get_all_menu();
		
		foreach ($menu_id as $k => $v) {
			
			foreach ($menu_list as $k1 => $v1) {
				
				if($v==$v1['id']){
					$m['group_id']=$group_id;
					$m['menu_id']=$v;					
					$m['name']=!empty($v1['url'])?$v1['url']:'';
					$this->db->insert('osc_admin_auth_rule',$m);
				}
				
			}					
			
		}
	}




}


